﻿using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace IcsCS.NHibernate.Cmd
{
    class ML
    {
        public ML()
        {
        }
        public int Id { get; set; } = 0;
        public string Name { get; set; }
    }
    class Program
    {
        public static object LockObj = new { };
        public static List<ML> List = new List<ML>();
        public static int idx = 1;
        static void Main(string[] args)
        {
            var text = string.Empty;
            //Task.Run(() =>
            //{
            //    SetO("Task 1");
            //});
            //Task.Run(() =>
            //{
            //    SetO("Task 2");
            //});
            //Task.Run(() =>
            //{
            //    SetO("Task 3");
            //});
            //Task.Run(() =>
            //{
            //    SetO("Task 4");
            //});
            //Task.Run(() =>
            //{
            //    SetO("Task 5");
            //});
            //SetO("Task Main");
            int count = 5;
            while (true)
            {
                Task.Delay(1000).Wait();
                var m = new Mutex(initiallyOwned: true, "mutex_1", out bool createNew);

                if (createNew)
                {
                    text = "MENK" + DateTime.Now;
                }
                if (count== 0) { 
                    m.Close();
                    count = 5; 
                }
                count--;
                Console.WriteLine(JsonConvert.SerializeObject(List));
                Console.WriteLine(text);
            }
        }

        static void SetO(string name)
        {
            Console.WriteLine("lock out name:" + name);
            lock (LockObj)
            {
                Task.Delay(3000).Wait();
                Console.WriteLine("lock in name:" + name);
                List.Add(new ML() { Name = name, Id = idx++ });
            }

        }

    }
}
